#include<iostream>
using namespace std;
#include<vector>
class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int n, int k) {
        vector<int> vec(n + 1, INT_MAX);
        vec[k] = 0;
        while (1) {
            int flag = 1;
            for (int i = 0; i < times.size(); ++i) {
                if (vec[times[i][0]] != INT_MAX && (vec[times[i][1]] > vec[times[i][0]] + times[i][2])) {
                    vec[times[i][1]] = vec[times[i][0]] + times[i][2];
                    flag = 0;
                }
            }
            if (flag)
                break;
        }
        int ans = 0;
        for (int i = 1; i <= n; ++i)
            if (vec[i] != INT_MAX)
                ans = max(ans, vec[i]);
            else
                return -1;
        return ans;
    }
};